﻿using MyDiskInfo.DataStruct;
using MyDiskInfo.Service;
using OpenHardwareMonitor.Hardware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utils;

namespace MyDiskInfoService.Utils
{
    /// <summary>
    /// 获取CPU信息
    /// </summary>
    public class CpuInfoUtil
    {
        private Computer _computer;
        private HardwareVisitor _hardwareVisitor;

        public CpuInfoUtil()
        {
            _computer = new Computer();
            _hardwareVisitor = new HardwareVisitor();

            ThreadHelper.Run(() =>
            {
                _computer.Open();
                _computer.CPUEnabled = true;
            });
        }

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        public CpuModel GetInfo()
        {
            CpuModel model = new CpuModel();

            _computer.Accept(_hardwareVisitor);

            foreach (IHardware hardware in _computer.Hardware)
            {
                double load = 0;
                double clock = 0;
                double temperature = 0;
                double power = 0;

                double clockCount = 0;

                if (hardware.HardwareType == HardwareType.CPU)
                {
                    foreach (ISensor sensor in hardware.Sensors)
                    {
                        if (sensor.SensorType == SensorType.Load && sensor.Name.Contains("CPU Total") && sensor.Value != null)
                        {
                            load = sensor.Value ?? 0;
                        }
                        if (sensor.SensorType == SensorType.Clock && sensor.Name.Contains("CPU Core") && sensor.Value != null)
                        {
                            clockCount++;
                            clock += sensor.Value ?? 0;
                        }
                        if (sensor.SensorType == SensorType.Temperature && sensor.Name.Contains("CPU Core") && sensor.Value != null)
                        {
                            if (sensor.Value.Value > temperature) temperature = sensor.Value.Value;
                        }
                        if (sensor.SensorType == SensorType.Power && sensor.Name.Contains("CPU Cores") && sensor.Value != null)
                        {
                            power = sensor.Value ?? 0;
                        }
                    }
                }

                if (clockCount > 0) clock = clock / clockCount;

                model.Load = load;
                model.Clock = Math.Round(clock / 1000.0, 2);
                model.Temperature = temperature;
                model.Power = power;
            }

            return model;
        }
    }
}
